<template>
    <div>
        <div class="orderList" style="">
            <h3>邀请码列表</h3>
            <!-- <template>
                    <el-input style="width:30%;"   class='input' prefix-icon="el-icon-search" clearable @change="handlChange"  v-model="newwxUid" placeholder="输入订单号查询"></el-input>
                    <el-button type="primary"    @click="checkCode()" icon="el-icon-search">搜索</el-button>
                </template> -->
            <div style="float:right;margin:20px 0">
                <el-button type="primary" class="right" @click="addCode()">生成邀请码</el-button>
                <el-button type="primary" @click="exportTableAll()">导出全部</el-button>
                <!-- 分页导出 -->
                <!-- <el-button  type="primary" @click="exportTable()">导出</el-button>
                    <template>
                        <el-input-number v-model="count"  :min="0" :max="1000" label="描述文字"></el-input-number>
                    </template> -->
            </div>
            <!-- <el-button type="text" @click="centerDialogVisible = true">点击打开 Dialog</el-button> -->

            <el-dialog title="" :visible.sync="centerDialogVisible" width="30%" center>
                <div style="text-align:center">
                    <span style="font-size:16px;padding:0 10px">生成数量:</span>
                    <template>
                        <el-input-number style="width:250px" v-model="ruleForm.num" :min="0" :max="1000" :step="5"></el-input-number>
                    </template>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
                </span>
            </el-dialog>
            <!-- <div class='popup-detail storeCode'  v-if='isShow' >
                    <el-form :model="ruleForm"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="生成数量:" prop="num" style="margin-bottom:30px;">
                            <el-input-number class='input' :min="0" :max="1000" v-model="ruleForm.num" :step="5" ></el-input-number>
                        </el-form-item>
                        <el-button class= '' type="primary" size="" @click="submitForm('ruleForm')">确定</el-button>
                        <el-button class= '' type="primary" size="" @click="close('ruleForm')">取消</el-button>
                    </el-form>
                </div>   -->

            <el-table class="table-common" ref="multipleTable" :data=" data " style="width: 100%; margin-top:30px;">
                <el-table-column prop="id" label="id" width="180">
                </el-table-column>
                <el-table-column prop="inviteCode" label="邀请码" width="180">
                </el-table-column>
                <el-table-column label="邀请码状态" prop="codeStatus" width="180">
                    <template slot-scope="scope">{{scope.row.codeStatus == '1' ? '有效' : '无效'}}</template>
                </el-table-column>

                <el-table-column label="生成时间" prop="createTime" width="180">
                    <template slot-scope="scope">{{ $formate(scope.row.createTime,'yyyy-MM-dd hh:mm:ss') }}</template>
                </el-table-column>
                <!-- <el-table-column
                
                    label="过期时间"
                    prop="expireTime"
                    width="180">
                        <template slot-scope="scope">{{ $formate(scope.row.expireTime,'yyyy-MM-dd hh:mm:ss') }}</template>
                    </el-table-column> -->

                <!-- <el-table-column
                        label="操作"
                        width="100"
                    >
                        <template slot-scope="scope">
                            <el-button type="text" @click="editOrder(scope.row)" size="small">查看</el-button>
                          
                        </template>
                    </el-table-column> -->
            </el-table>
            <!-- 分页 -->
            <section class="pagination" v-if=" total >10">
                <template v-if="page == 1">
                    <el-button type="primary" disabled>上一页</el-button>
                </template>
                <template v-else>
                    <el-button type="primary" @click="pagePrev">上一页</el-button>
                </template>
                <template v-if="Math.ceil(total/10) <= page">
                    <el-button type="primary" disabled>下一页</el-button>
                </template>
                <template v-else>
                    <el-button type="primary" @click="pageNext">下一页</el-button>
                </template>
                <template>
                    <el-button disabled>共{{total}}条</el-button>
                    <el-button disabled>第{{page}}页</el-button>
                </template>
            </section>

        </div>
    </div>
</template>
<script>
import { codeList, createCode } from "../../data/postData.js";
export default {
    data() {
        return {
            Page: JSON.parse(localStorage.getItem("Page")),
            data: null,
            total: "",
            page: "1",
            size: "5",
            wxUid: "0",
            isShow: false,
            centerDialogVisible: false,
            exportCodeData: null,
            allCodeList: null,
            count: "1",
            ruleForm: {
                num: ""
            }
        };
    },
    mounted() {
        if (this.Page && this.Page != null) {
            this.page = this.Page.page;

            this.getCode(this.Page.page);
        } else {
            this.page = 1;
            this.getCode(1);
        }
        // this.exportCodeList(this.count)分页导出
        this.exportCodeList(); //全部导出
    },
    methods: {
        //导出全部
        exportTableAll() {
            this.excel =
                "邀请码" +
                this.$formate(new Date().getTime(), "yyyy-MM-dd hh:mm:ss");
            this.export2Excel();
        },
        //导出excel
        async exportTable() {
            console.log(this.count, "导出表哥啦");
            this.exportCodeList(+this.count - 1, () => {
                this.excel =
                    "邀请码" +
                    this.$formate(new Date().getTime(), "yyyy-MM-dd hh:mm:ss");
                this.export2Excel();
            });
        },
        exportCodeList(count, cb) {
            let params = {
                data: {
                    page: "1",
                    size: "100000",
                    wxUid: "0"
                }
            };
            this.$fetch
                .post(codeList, params)
                .then(res => {
                    console.log(res.data, "导出");
                    // this.exportCodeData = res.data
                    var codeArr = [];
                    var codeListArr = [];
                    res.data.forEach(item => {
                        if (item.codeStatus == 1) {
                            codeArr.push(item);
                        }
                    });
                    codeArr.forEach(item1 => {
                        item1.createTime = this.$formate(
                            item1.createTime,
                            "yyyy-MM-dd hh:mm:ss"
                        );
                        item1.codeStatus =
                            item1.codeStatus == 1 ? "有效" : "无效";
                    });
                    this.allCodeList = codeArr;
                    //分页导出
                    // console.log(codeArr,'codeArr')
                    // var SplitArray = function(N,Q){
                    //     var R = [],F;
                    //     for (F = 0;F < Q.length;) R.push(Q.slice(F,F += N))
                    //     return R
                    // }
                    // codeListArr = SplitArray(100,codeArr)
                    // console.log(codeListArr,'codeListArr')
                    // codeListArr.forEach((item2,indexa)=>{
                    //     this.exportCodeData = item2
                    // })
                    // if(count<codeListArr.length){
                    //     console.log(count)
                    //     this.exportCodeData = codeListArr[count]
                    //     cb&&cb()
                    //     console.log(this.exportCodeData,'count',count)
                    // }else{
                    //     this.$message({
                    //         message:'没有更多数据了',
                    //         type:'warning'
                    //     })
                    // }

                    console.log(
                        this.exportCodeData,
                        "this.exportCodeDatadeArr"
                    );
                })
                .catch(err => {});
        },
        export2Excel() {
            console.log(this.allCodeList, "倒出");
            // 　　　　　　  require.ensure([], () => {
            //     　　　　　　　　const { export_json_to_excel } = require('../../vendor/Export2Excel');
            //     　　　　　　　　const tHeader = [ '生成时间','邀请码', '邀请码状态']; //对应表格输出的title
            //     　　　　　　　　const filterVal = ['createTime','inviteCode', 'codeStatus']; // 对应表格输出的数据
            //     　　　　　　　　//const list = this.exportCodeData;分页导出
            //                     const list = this.allCodeList;//全部导出
            //     　　　　　　　　const data = this.formatJson(filterVal, list);
            //     　　　　　　　　export_json_to_excel(tHeader, data, this.excel); //对应下载文件的名字
            // 　　　　　　  })
            //this.export2Excel()
            var allCodeList = this.allCodeList;
            //this.export2Excel()
            var str = "生成时间,邀请码,邀请码状态" + "\n";
            //str+='\uFEFF';
            //增加\t为了不让表格显示科学计数法或者其他格式
            for (var i = 0; i < allCodeList.length; i++) {
                //   for(var item in allCodeList[i]){
                str += '"' + allCodeList[i]["createTime"] + '"' + ",";
                str += allCodeList[i]["inviteCode"] + "\t" + ",";
                str += '"' + allCodeList[i]["codeStatus"] + '"' + ",";
                str += "\n";
            }
            //encodeURIComponent解决中文乱码
            var uri =
                "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);

            function requiredFeaturesSupported() {
                return BlobConstructor() && msSaveOrOpenBlobSupported();
            }

            function BlobConstructor() {
                if (!window.Blob) {
                    return false;
                } // if

                return true;
            } // BlobConstructor

            function msSaveOrOpenBlobSupported() {
                if (!window.navigator.msSaveOrOpenBlob) {
                    return false;
                } // if

                return true;
            } // msSaveOrOpenBlobSupported

            //通过创建a标签实现
            var link = document.createElement("a");
            link.href = uri;

            if (requiredFeaturesSupported()) {
                var blobObject = new Blob([str], {
                    type: "text/csv;charset=utf-8"
                });
                window.navigator.msSaveOrOpenBlob(
                    blobObject,
                    this.excel + ".csv"
                );
            } else {
                //对下载的文件命名
                link.download = this.excel + ".csv";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        addCode() {
            //    this.$router.push({path:'/addUserCode'})
            this.centerDialogVisible = true;
            this.ruleForm.num = "0";
            //this.isShow = true
        },
        close() {
            this.isShow = false;
        },
        submitForm() {
            var params = {
                data: {
                    wxUid: "0",
                    num: "" + this.ruleForm.num,
                    class: "0"
                }
            };
            this.$fetch
                .post(createCode, params)
                .then(res => {
                    console.log(res.data);
                    this.$message({
                        message: res.message,
                        type: "success",
                        duration: 1000
                    });
                    setTimeout(() => {
                        this.centerDialogVisible = false;
                        // this.isShow = false
                        this.getCode(1);
                    }, 1200);
                })
                .catch(err => {
                    this.$message({
                        message: err.message,
                        type: "error",
                        duration: 1000
                    });
                });
        },
        checkCode() {
            this.getCode();
        },
        getCode(page) {
            var params = {
                data: {
                    wxUid: "0",
                    page: page,
                    size: "10"
                }
            };
            this.$fetch
                .post(codeList, params)
                .then(res => {
                    this.data = res.data;
                    this.total = res.total;
                    console.log(this.total);
                    console.log(res.data);
                })
                .catch(err => {});
        },
        pagePrev() {
            this.page--;
            this.getCode(this.page);
            localStorage.setItem("Page", JSON.stringify({ page: this.page }));
        },
        pageNext() {
            this.page++;
            this.getCode(this.page);
            localStorage.setItem("Page", JSON.stringify({ page: this.page }));
        }
    }
};
</script>
<style scoped lang="less">
.orderList {
    width: calc(~"100% - 250px");
    margin-top: 66px;
    margin-left: 230px;
    float: left;
    h3 {
        margin: 20px 0px;
        //font-size:24px;
    }
    // .right{
    //     float:right;
    //     margin:20px 10px;
    // }
    .input {
        width: 300px;
    }
}
.pagination {
    display: flex;
    justify-content: center;
    margin: 20px 0;
}
.storeCode {
    width: 500px;
    height: 200px;
    text-align: center;
    overflow: hidden;
}
.demo-ruleForm {
    margin-top: 30px;
}
</style>
